package leetcode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-25 21:16
 **/
public class LeetCode199 {

    /**
     * BFS层序遍历
     * @param root
     * @return
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        //临时节点
        TreeNode temp = null;
        deque.offer(root);
        while (!deque.isEmpty()) {
            //当前层元素个数
            int size = deque.size();
            for (int i = 0; i < size; i++) {
                temp = deque.poll();
                if (temp.left != null) {
                    deque.offer(temp.left);
                }
                if (temp.right != null) {
                    deque.offer(temp.right);
                }
                //遍历到一层最后一个节点，就将值放到list中。
                if (i == size - 1) {
                    list.add(temp.val);
                }
            }
        }
        return list;
    }

}
